﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CommerceOne.Common;
using CommerceOne.Controllers;
using CommerceOne.Widgets.Commons;

namespace CommerceOne.Widgets.Paging
{
    public class PagingController : ControllerBase
    {
        public PagingViewModel GetViewModel (Parameters parameter)
        {
            if (parameter == null) throw new Exception("Parameter cannot be null");
            if (parameter.ObjectId == null) throw new Exception("ObjectID in the Parameter cannot be null");
            string queryString = this.HttpContextBase.Request.Url == null ? string.Empty : this.HttpContextBase.Request.Url.Query;

            var viewModel = new PagingViewModel {Pages = new List<UrlAddress>()};

            int remain = 0;
            int totalPage = Math.DivRem(parameter.TotalRecord, parameter.PageSize, out remain);
            if (remain > 0) totalPage++;

            for (int i = 1; i<=totalPage; i++)
            {
                var address = new UrlAddress
                                  {
                                      Address =
                                          UrlBuilderService.Instance.GetUrlRoute(PageType.ProductList,
                                                                                 parameter.ObjectId.Value, i,
                                                                                 parameter.ObjectTitle, queryString),
                                      Text = i.ToString()
                                  };
                if (i == parameter.CurrentPage) address.IsCurrenPage = true;
                viewModel.Pages.Add(address);
            }

            if (parameter.CurrentPage > 1) viewModel.PreviousLink = viewModel.Pages[parameter.CurrentPage - 2];
            if (parameter.CurrentPage < totalPage) viewModel.NextLink = viewModel.Pages[parameter.CurrentPage];

            return viewModel;

        }
    }
}